package com.dwxt.sport.business.service;

import com.dwxt.common.base.StatusCode;
import com.dwxt.common.constant.VariableConstants;
import com.dwxt.common.util.SnowIdUtil;
import com.dwxt.sport.business.dao.SmartDeviceEquipmentMapper;
import com.dwxt.sport.business.dao.SmartDeviceMapper;
import com.dwxt.sport.business.entity.SmartDevice;
import com.dwxt.sport.business.entity.SmartDeviceEquipment;
import com.dwxt.sport.business.vo.smartDevice.InsertOrUpdateSmartDeviceEquipmentVo;
import com.dwxt.sport.business.vo.smartDevice.InsertOrUpdateSmartDeviceVo;
import com.dwxt.sport.business.vo.smartDevice.SelectSmartDeviceVo;
import com.dwxt.sport.constant.CommonConstant;
import com.dwxt.sport.exception.CustomException;
import com.dwxt.sport.util.BusinessValidationUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * 智能装备 Service
 *
 * @author Kuang.JiaZhuo
 * @date 2020-07-29 11:53
 */
@Service
public class SmartDeviceService {

    @Resource
    SmartDeviceMapper smartDeviceMapper;

    @Resource
    SmartDeviceEquipmentMapper equipmentMapper;

    /**
     * @方法名：selectSmartDeviceByCondition
     * @描述： 按条件查询智能装备列表(带分页)
     * @作者： kjz
     * @日期： Created in 2020/7/29 14:25
     */
    public PageInfo<SmartDevice> selectSmartDeviceByCondition(SelectSmartDeviceVo selectVo) {
        PageHelper.startPage(selectVo.getPageNum(), selectVo.getPageSize());
        List<SmartDevice> list = smartDeviceMapper.selectSmartDeviceByCondition(selectVo);
        list.forEach(smartDevice -> {
            smartDevice.setEquipmentsImgUrl(CommonConstant.FILE_SERVER+smartDevice.getEquipmentsImgUrl());
        });
        PageInfo<SmartDevice> pageInfo = new PageInfo(list);
        return pageInfo;
    }

    /**
     * @方法名：insertSmartDevice
     * @描述： 新增智能装备
     * @作者： kjz
     * @日期： Created in 2020/7/29 14:17
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertSmartDevice(InsertOrUpdateSmartDeviceVo insertVo) {
        SmartDevice smartDevice = new SmartDevice()
                .setId(SnowIdUtil.getInstance().nextId())
                .setCreateTime(LocalDateTime.now())
                .setIsDelete(VariableConstants.STRING_CONSTANT_0)
                .setStreetId(insertVo.getStreetId()) //街道id
                .setName(insertVo.getName()) //设备名称
                .setEquipmentsImgUrl(insertVo.getEquipmentsImgUrl()) //设备图片地址
                .setRecommendedCoverage(insertVo.getRecommendedCoverage()); //建议覆盖率

        return smartDeviceMapper.insert(smartDevice);
    }

    /**
     * @方法名：updateSmartDevice
     * @描述： 更新智能装备
     * @作者： kjz
     * @日期： Created in 2020/7/29 14:22
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateSmartDevice(InsertOrUpdateSmartDeviceVo updateVo) {
        String id = updateVo.getId();
        if(!BusinessValidationUtil.verifyId(id)){
            throw new CustomException(StatusCode.ID_IS_NULL);
        }
        SmartDevice smartDevice = new SmartDevice()
                .setUpdateTime(LocalDateTime.now())
                .setName(updateVo.getName()) //设备名称
                .setEquipmentsImgUrl(updateVo.getEquipmentsImgUrl()) //设备图片地址
                .setRecommendedCoverage(updateVo.getRecommendedCoverage()); //建议覆盖率

        if(null != updateVo.getStreetId()){
            smartDevice.setStreetId(null);
        }

        return smartDeviceMapper.updateByPrimaryKeySelective(smartDevice);
    }


    /**
     * @方法名：deleteSmartDeviceByIds
     * @描述： 根据ids批量删除智能装备
     * @作者： kjz
     * @日期： Created in 2020/7/29 14:25
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteSmartDeviceByIds(String ids) {
        if(ids == null || "".equals(ids)) {
            throw new CustomException(StatusCode.ID_IS_NULL);
        }

        String[] idArray = ids.split(",");
        //删除消息和工作人员的关联
        return this.smartDeviceMapper.deleteSmartDeviceByIds(idArray);
    }


    /************************************************************   关联设备   ***************************************************************************/

    /**
     * @方法名：deleteSmartDeviceEquipmentByIds
     * @描述： 根据ids批量删除能装备关联设备
     * @作者： kjz
     * @日期： Created in 2020/7/29 15:41
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteSmartDeviceEquipmentByIds(String ids) {
        if(ids == null || "".equals(ids)) {
            throw new CustomException(StatusCode.ID_IS_NULL);
        }

        String[] idArray = ids.split(",");
        //删除消息和工作人员的关联
        int result = this.equipmentMapper.deleteSmartDeviceEquipmentByIds(idArray);
        if(result>0){
            String id = idArray[0];
            String smartDeviceId = equipmentMapper.selectByPrimaryKey(id).getSmartDeviceId();
            this.updateSmartDeviceById(smartDeviceId);
        }
        return result;
    }

    /**
     * @方法名：selectSmartDeviceEquipmentByCondition
     * @描述： 根据智能装备的id查询关联设备的列表(带分页)
     * @作者： kjz
     * @日期： Created in 2020/7/29 15:45
     */
    public PageInfo<SmartDeviceEquipment> selectSmartDeviceEquipmentByCondition(Integer pageNum, Integer pageSize, String smartDeviceId) {
        PageHelper.startPage(pageNum==null?1:pageNum, pageSize==null?10:pageSize);
        List<SmartDeviceEquipment> list = equipmentMapper.selectSmartDeviceEquipmentByCondition(smartDeviceId);
        PageInfo<SmartDeviceEquipment> pageInfo = new PageInfo(list);
        return pageInfo;
    }

    /**
     * @方法名：insertOrUpdateSmartDeviceEquipment
     * @描述： 新增或更新智能装备关联的设备
     * @作者： kjz
     * @日期： Created in 2020/7/29 15:53
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertOrUpdateSmartDeviceEquipment(InsertOrUpdateSmartDeviceEquipmentVo insertOrUpdateVo) {

        String id = insertOrUpdateVo.getId();
        SmartDeviceEquipment smartDeviceEquipment = new SmartDeviceEquipment()
                .setEquipmentId(insertOrUpdateVo.getEquipmentId()) //设备id
                .setUnitType(insertOrUpdateVo.getUnitType()) //设备型号
                .setSession(insertOrUpdateVo.getSession()) //使用频率(次/天)
                .setBuildingUse(insertOrUpdateVo.getBuildingUse()) //使用人次
                .setAvg(insertOrUpdateVo.getAverageUsageTime()) //平均使用时长(单位:min)
                .setTotalUsageTime(insertOrUpdateVo.getTotalUsageTime()) //使用总时长(单位:min)
                .setDeviceStates(insertOrUpdateVo.getDeviceStates());

        int result = 0;
        String smartDeviceId = insertOrUpdateVo.getSmartDeviceId();
        if(null==id || id.trim().length()==0) {

            if (null == smartDeviceId || smartDeviceId.trim().length() == 0) {
                throw new CustomException(StatusCode.SMART_DEVICE_ID_IS_NULL);
            }

           //新增
            smartDeviceEquipment.setSmartDeviceId(smartDeviceId)
                    .setId(SnowIdUtil.getInstance().nextId())
                    .setCreateTime(LocalDateTime.now())
                    .setIsDelete(VariableConstants.STRING_CONSTANT_0);
            result = equipmentMapper.insert(smartDeviceEquipment);
//            System.err.println("result="+result);
        }else{
            //更新
            smartDeviceEquipment.setId(id).setUpdateTime(LocalDateTime.now());
            result = equipmentMapper.updateByPrimaryKeySelective(smartDeviceEquipment);
        }

        if(result>0){
            this.updateSmartDeviceById(smartDeviceId);
        }

        return result;
    }

    /**
     * @方法名：updateSmartDeviceById
     * @描述： 新增或更新智能装备的设备之后~更新 智能装备需要计算的数据
     * @作者： kjz
     * @日期： Created in 2020/8/5 10:45
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateSmartDeviceById(String smartDeviceId) {
        HashMap map = equipmentMapper.selectStatisticsBySmartDeviceId(smartDeviceId);
        SmartDevice smartDevice = new SmartDevice()
                .setAmount(Integer.valueOf(map.get("amount").toString()))
                .setEquipmentUsage(Integer.valueOf(map.get("equipmentUsage").toString()))
                .setAvg(Double.parseDouble(map.get("avgElapsedTime").toString()))
                .setUpdateTime(LocalDateTime.now())
                .setId(smartDeviceId);
        return smartDeviceMapper.updateByPrimaryKeySelective(smartDevice);
    }
}
